package com.uniview.util;

import org.apache.commons.lang3.StringUtils;

import com.uniview.enums.EOrderMode;

public class HqlUtils {

	/**
	 * 组装Hql count语句，例: select count(*) from tabName
	 * 
	 * @param hql
	 * @return
	 */
	public static String buildCountHQL(String hql) {
		if (StringUtils.isEmpty(hql))
			return hql;
		if (hql.trim().toLowerCase().startsWith("from")) {
			return "select count(*) " + hql;
		} else {
			int idx = hql.trim().toLowerCase().indexOf("from");
			if (idx > 0) {
				return "select count(*) " + hql.substring(idx);
			}
		}
		return hql;
	}

	/**
	 * 循环Map中的key作为查询字段，并根据排序字段，拼装成查询语句
	 * 
	 * @param hql
	 *            hql 语句
	 * @param params
	 *            查询字段参数
	 * @param orderMode
	 *            排序方式
	 * @param orderCols
	 *            排序字段
	 * @return
	 */
	public static String buildOrderHQL(String hql, EOrderMode orderMode, String... orderCols) {
		if (StringUtils.isBlank(hql))
			return null;
		StringBuffer hqlBuf = new StringBuffer(hql);
		if (orderMode != null && orderCols != null) {
			String cols = "";
			for (String col : orderCols) {
				cols += col + ",";
			}
			if (cols.endsWith(",")) {
				cols = cols.substring(0, cols.length() - 1);
			}
			if (cols.length() > 0) {
				hqlBuf.append(" order by ").append(cols).append(" ").append(orderMode.toString());
			}
		}
		return hqlBuf.toString();
	}

}
